package cn.wowjoy.office.homepage;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.view.indicator.BannerComponent;

import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.appedit.AppEditActivity;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseFragment;
import cn.wowjoy.office.common.adapter.BannerAdapter;
import cn.wowjoy.office.common.adapter.ComAppAdapter;
import cn.wowjoy.office.common.decoration.GridSpacesItemDecoration;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.response.AppInfo;
import cn.wowjoy.office.data.response.BannerInfo;
import cn.wowjoy.office.databinding.FragmentHomeBinding;
import cn.wowjoy.office.materialinspection.applyfor.StockApplyIndexActivity;
import cn.wowjoy.office.materialinspection.check.CheckIndexActivity;
import cn.wowjoy.office.materialinspection.stockout.otherout.StockOtherOutActivity;
import cn.wowjoy.office.materialinspection.xunjian.MaterialActivity;
import cn.wowjoy.office.materialmanage.materiallist.MaterialListActivity;
import cn.wowjoy.office.personal.PersonalActivity;
import cn.wowjoy.office.pm.view.PmManagerActivity;
import cn.wowjoy.office.search.SearchActivity;
import cn.wowjoy.office.utils.dialog.DialogUtils;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends NewBaseFragment<FragmentHomeBinding,HomeViewModel> implements BannerAdapter.OnItemClickListener, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private BannerComponent bannerComponent;
    private BannerAdapter bannerAdapter;
    private static final int REQUEST_CODE_CAMERA = 1;
    private ItemTouchHelper itemTouchHelper;
    private MDialog waitDialog;


    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState) {

            binding.setViewmodel(viewModel);

        //banner暂时不做
//        bannerComponent = new BannerComponent(binding.bannerIndicator,binding.bannerViewPager,true);
//        homePresenter.getViewModel().bannerAdapter.setOnItemClickListener(this);
//        bannerComponent.setAdapter(homePresenter.getViewModel().bannerAdapter);
//        //默认就是800毫秒，设置单页滑动效果的时间
////        bannerComponent.setScrollDuration(800);
//        //设置播放间隔时间，默认情况是3000毫秒
//        bannerComponent.setAutoPlayTime(2500);

//        ArrayAdapter<String> arrayAdapter=new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,data);
//        binding.searchEditText.setAdapter(arrayAdapter);
//        binding.searchEditText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getContext(),data[position],Toast.LENGTH_SHORT).show();
//            }
//        });


//        binding.messageCenter.showTextBadge("");
        binding.messageCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                binding.messageCenter.hiddenBadge();
                startActivity(new Intent(getActivity(), PersonalActivity.class));
            }
        });

        binding.gridList.setLayoutManager(new GridLayoutManager(getContext(),3));
//        binding.gridList.setPullRefreshEnabled(false);
        setEvent();
        binding.gridList.setAdapter(viewModel.comAppAdapter);
        int space = getResources().getDimensionPixelSize(R.dimen.space_bootom);
        binding.gridList.addItemDecoration(new GridSpacesItemDecoration(space, true));
//        homePresenter.getViewModel().setEventListener();
//        itemTouchHelper = homePresenter.getViewModel().getItemTouchHelper();
//        itemTouchHelper.attachToRecyclerView(binding.gridList);
//        binding.gridList.addOnItemTouchListener(new OnRecyclerItemClickListener(binding.gridList) {
//            @Override
//            public void onItemClick(RecyclerView.ViewHolder vh) {
//
//            }
//
//            @Override
//            public void onItemLongClick(RecyclerView.ViewHolder vh) {
//                itemTouchHelper.startDrag(vh);
//            }
//        });
        binding.goToSearch.setOnClickListener(this);
        binding.more.setOnClickListener(this);
        onResponse();
        initSwiper();
    }
    private void initSwiper() {
        binding.refresh.setColorSchemeResources(
                R.color.C_5777A6
        );
        binding.refresh.setSize(SwipeRefreshLayout.DEFAULT);
        binding.refresh.setOnRefreshListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_CAMERA:
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    scan();
//                }
                if (grantResults.length > 0) {
                    for (int gra : grantResults) {
                        if (gra != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                    }
                }
                viewModel.scan();
                break;
        }
    }

    @Override
    protected void onResumeLazy() {
        super.onResumeLazy();
         request();
    }

    @Override
    protected void onStartLazy() {
        super.onStartLazy();
//        bannerComponent.startAutoPlay();
    }

    @Override
    protected void onStopLazy() {
        super.onStopLazy();
//        bannerComponent.stopAutoPlay();
    }

    @Override
    protected Class<HomeViewModel> getViewModel() {
        return HomeViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }
    //请求数据
    private void request() {
        viewModel.getAuidsPms();
//        viewModel.myAppinfos();
    }


    private void onResponse() {
        viewModel.mParams.observe(this, new Observer<LiveDataWrapper<List<AppInfo>>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<List<AppInfo>> auidsPmsResponseLiveDataWrapper) {
                switch (auidsPmsResponseLiveDataWrapper.status){
                    case LOADING:
                        if(!binding.refresh.isShown()){
                            DialogUtils.waitingDialog(getActivity());
                        }
//                        DialogUtils.waitingDialog(getActivity());
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(getActivity());
                        hideFresh();
                        if(null != auidsPmsResponseLiveDataWrapper.data){
                            viewModel.setDatas(auidsPmsResponseLiveDataWrapper.data);
                            MenuHelper.setAuidList(auidsPmsResponseLiveDataWrapper.data);
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(getActivity());
                        hideFresh();
                        handleException(auidsPmsResponseLiveDataWrapper.error,true);
                        break;
                }
            }
        });
    }

//    @Override
//    protected ViewGroup getErrorViewRoot() {
//        return binding.gridList;
//    }
    /**
     * 应用搜索
     */
    public void search(){
        Intent intent = new Intent(getActivity(), SearchActivity.class);
        startActivity(intent);
    }


    /**
     * 应用编辑页面
     */
    public void jumpMore(){
        Intent intent = new Intent(getActivity(), AppEditActivity.class);
        startActivity(intent);
    }
    @Override
    public void onItemClick(int position, BannerInfo bannerInfo) {
        Toast.makeText(getContext(),"第"+position,Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.go_to_search:
                search();
                break;
            case R.id.more:
                jumpMore();
                break;
        }

    }

    public void setEvent(){
        viewModel.comAppAdapter.setOnEventListener(new ComAppAdapter.OnEventListener() {
            @Override
            public void onItemClick(AppInfo appInfo) {
                switch (MenuHelper.getAppNames().get(appInfo.getPmsKey())){
                    case "库存盘点": //庫存盤點
                        ARouter.getInstance().build("/materialmanage/inventory/materialinventory").navigation();
                        break;
                    case "巡检管理":
                        Intent materialActivity = new Intent(getActivity(), MaterialActivity.class);
                        startActivity(materialActivity);
                        break;
                    case "库存详情":
                        ARouter.getInstance().build("/materialmanage/stock/materialstock").navigation();
                        break;
                    case "主数据":
                        Intent intent1 = new Intent(getActivity(), MaterialListActivity.class);
                        startActivity(intent1);
                        break;
                    case "更多":
                        Intent intent = new Intent(getActivity(), AppEditActivity.class);
                        startActivity(intent);
                    case "盘点管理":
                        Intent intent3 = new Intent(getActivity(), CheckIndexActivity.class);
                        startActivity(intent3);
                        break;
                    case "其他出库":
                        Intent intent4 = new Intent(getActivity(), StockOtherOutActivity.class);
                        startActivity(intent4);
                        break;
                    case "申请出库":
                        Intent intent1014 = new Intent(getActivity(), StockApplyIndexActivity.class);
                        startActivity(intent1014);
                        break;
                    case "调拨出库":
                        ARouter.getInstance().build("/applystock/applystocklist")
                                .withInt("type", Constants.RECEIPTS_CODE_ALLOT)
                                .navigation();
                        break;
                    case "PM管理":
                        Intent intent1016 = new Intent(getActivity(), PmManagerActivity.class);
                        startActivity(intent1016);
                        break;
                    case "申领出库":
                        ARouter.getInstance().build("/applystock/applystocklist")
                                .withInt("type", Constants.RECEIPTS_CODE_APPLY)
                                .navigation();
                        break;
                }
            }

            @Override
            public void onItemLongClick(AppInfo appInfo) {
//                Toast.makeText(homeFragment.getContext(),"请点击更多跳转至编辑页面编辑应用",Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRefresh() {
        request();
    }
    public void hideFresh(){
        if (binding.refresh.isShown()) {
            binding.refresh.post(new Runnable() {
                @Override
                public void run() {

                    binding.refresh.setRefreshing(false);

                }
            });
        }
    }
//    @Override
//    public void onClick(View v) {
//        List<String> group = new ArrayList<>();
//        group.add(Manifest.permission_group.CAMERA);
//        if (requestRuntimePermissions(PermissionUtil.permissionGroup(group, null), REQUEST_CODE_CAMERA)) {
//            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                // TODO: Consider calling
//                //    ActivityCompat#requestPermissions
//                // here to request the missing permissions, and then overriding
//                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                //                                          int[] grantResults)
//                // to handle the case where the user grants the permission. See the documentation
//                // for ActivityCompat#requestPermissions for more details.
//                return;
//            }
//            homePresenter.scan();
//        }
//    }
}
